package com.hz.house.token;

import java.util.Calendar;

import javax.crypto.spec.SecretKeySpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hz.house.config.JWTConfig;

import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 *  提供JWT的token获取和解码.和原来的一模一样
 * @author lfw
 */

@Component
public class JWTUtil {

	@Autowired
	private JWTConfig jwtConfig;
	//密钥
	private SecretKeySpec secretKeySpec;
	
	private static Logger logger = LoggerFactory.getLogger(JWTUtil.class);
	
	private SecretKeySpec getSks() {
		if(secretKeySpec==null) 
			secretKeySpec = new SecretKeySpec("dev".getBytes(),
					SignatureAlgorithm.HS256.getJcaName());
		
		return secretKeySpec;
	}
	
	
    /**
     * 生成token
     * @return
     */
    public  String createToken(LoginUser user) {
        UaaClaims claims = new UaaClaims(user);
        Calendar exp = Calendar.getInstance();
        exp.add(Calendar.SECOND, this.jwtConfig.getExpiration());
        String token = Jwts
                .builder()
                .setClaims(claims)
                .setExpiration(exp.getTime())
                .compressWith(CompressionCodecs.DEFLATE)
                .signWith(SignatureAlgorithm.HS256, getSks())
                .compact();
        return token;
    }
    
    /**
     * token校验
     */
    public UaaClaims validate(String token) {
        if (token == null || token.isEmpty()) 
            return null;
        try {
            return UaaClaims.parse(Jwts.parser().setSigningKey(getSks())
                    .parseClaimsJws(token).getBody());
        } catch (MalformedJwtException e) {
            logger.error("token结构异常:{}", token);
        } catch (ExpiredJwtException e) {
            logger.error("token已经过期:{}", token);
        } catch (Exception e) {
            logger.error("token解析错误:" + token, e);
        }
        return null;
    }
}
